﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Serialization;
using System.IO;
using modBusTest;


namespace executeCommands
{
    public partial class Form1 : Form
    {
        BindingList<DataStorage> bindingSource1 = new BindingList<DataStorage>();
        //ProcessCommands handleCommands = new ProcessCommands();
        XmlSerializer serializer = new XmlSerializer(typeof(BindingList<DataStorage>));
        
        public Form1()
        {
            
            InitializeComponent();
            
            
            
            this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
            bool sucessfulread = false;

            if (File.Exists("out.xml"))
            {
                sucessfulread = true;
                File.Copy("out.xml", "out.xml.bak", true);
                using (StreamReader inHandle = new StreamReader("out.xml"))
                {
                    try
                    {
                        bindingSource1 = (BindingList<DataStorage>)serializer.Deserialize(inHandle);
                    }
                    catch (Exception err)
                    {
                        MessageBox.Show(err.Message);
                        sucessfulread = false;
                    }
                }
            }

            if (!sucessfulread)
            {
                bindingSource1 = new BindingList<DataStorage>();
                //DataStorage.portSettings.comPort = "COM13";
                //DataStorage.portSettings.baudSpeed = 9600;
                //DataStorage.portSettings.modbusId = 49;
                //DataStorage.portSettings.fileName = @"C:\Documents and Settings\e140818\My Documents\MasterModbusMapMacro2Stripped.txt";
            }
            state portsettings;
            if (File.Exists("settings.xml"))
            {
                XmlSerializer inHandle = new XmlSerializer(typeof(state));
                portsettings = (state)inHandle.Deserialize(new StreamReader("settings.xml"));
            }
            else
            {
                portsettings.baudSpeed = 9600;
                portsettings.comPort = "COM13";
                portsettings.fileName = @"C:\Documents and Settings\e140818\My Documents\MasterModbusMapMacro2Stripped.txt";
                portsettings.modbusId = 49;
                using (StreamWriter outHandle = new StreamWriter("settings.xml"))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(state));
                    serializer.Serialize(outHandle, portsettings);
                }
            }


            System.IO.Ports.SerialPort port = new System.IO.Ports.SerialPort(portsettings.comPort,
                portsettings.baudSpeed);

            command.port = port;
            command.modbusId = portsettings.modbusId;


            map.readDataMethod2(portsettings.fileName);

            setupBindings();


            //dataGridView1.MouseDoubleClick += new MouseEventHandler(dataGridView1_MouseDoubleClick);
            
            //this.Controls.Add(this.dataGridView1);
            //this.Refresh();
            //this.KeyDown += new KeyEventHandler(Form1_KeyDown);
            //dataGridView1.KeyDown += new KeyEventHandler(Form1_KeyDown);
        }
        modbusmap map = new modbusmap();
        void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode == Keys.I){
                bindingSource1.Insert(dataGridView1.CurrentCell.RowIndex,new DataStorage());
            }
            
        }

 

        void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            
            using(StreamWriter outHandle = new StreamWriter("out.xml")){
                serializer.Serialize(outHandle, bindingSource1);
            }

           
            
        }

        void setupBindings()
        {    //bindingSource1.Add(new DataStorage());
             //bindingSource1.Add(new DataStorage());
             //bindingSource1.Add(new DataStorage());

            
            
            
            
            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.AutoSize = false;
            dataGridView1.DataSource = bindingSource1;

            DataGridViewColumn column = new DataGridViewCheckBoxColumn();
            column.Width = 35;
            dataGridView1.Columns.Add(column);

            //column = new DataGridViewTextBoxColumn();
            //column.DataPropertyName = "command";
            //column.Name = "Commands";

            DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
            combo.DataSource = Enum.GetValues(typeof(DataStorage.commandEnum));
            //combo.ValueType = typeof(DataStorage.commandEnum);
            combo.DataPropertyName = "command";
            combo.Name = "Commands";
            //combo.ValueMember = 
            //return combo;
            combo.Width = 71;
            
            
            
            dataGridView1.Columns.Add(combo);

            column = new DataGridViewTextBoxColumn();
            column.DataPropertyName = "RegisterName";
            column.Name = "Register Name";
            column.Width = 270;
            dataGridView1.Columns.Add(column);



            column = new DataGridViewTextBoxColumn();
            column.DataPropertyName = "RegisterNumber";
            column.Name = "Register Number";
            column.Width = 60;
            dataGridView1.Columns.Add(column);

            column = new DataGridViewTextBoxColumn();
            column.DataPropertyName = "Value";
            column.Name = "Value";
            column.Width = 60;
            dataGridView1.Columns.Add(column);


            

            //bindingSource1.Add(new DataStorage());
            //bindingSource1.Add(new DataStorage());
            //bindingSource1.Add(new DataStorage());

            //dataGridView1.Update();
            column = new DataGridViewCheckBoxColumn();
            column.Width = 50;
            column.DataPropertyName = "success";
            column.Name = "Sucess";
            dataGridView1.Columns.Add(column);

            column = new DataGridViewTextBoxColumn();
            column.DataPropertyName = "comments";
            column.Name = "Comments";
            column.Width = 200;
            dataGridView1.Columns.Add(column);

            column = new DataGridViewTextBoxColumn();
            column.DataPropertyName = "errCode";
            column.Name = "Error Messages";
            column.Width = 200;
            dataGridView1.Columns.Add(column);

            //dataGridView1.CurrentCellChanged += new EventHandler(dataGridView1_CurrentCellChanged);
            //dataGridView1.CurrentCellDirtyStateChanged += new EventHandler(dataGridView1_CurrentCellChanged);
            dataGridView1.CellEndEdit += new DataGridViewCellEventHandler(dataGridView1_CurrentCellChanged);
        }

        void dataGridView1_CurrentCellChanged(object sender, EventArgs e)
        {
            try
            {
                if (dataGridView1.CurrentCell != null)
                {
                    if (dataGridView1.CurrentCell.OwningColumn.Name == "Register Number")
                    {
                        int columnIndex = dataGridView1.Columns["Register Name"].Index;
                        int rowindex = dataGridView1.CurrentCell.RowIndex;

                        mapFields tempMapFields = map.findParam(int.Parse(dataGridView1.CurrentCell.Value.ToString()));

                        dataGridView1[columnIndex, rowindex].Value = tempMapFields.paramName;
                    }

                    if (dataGridView1.CurrentCell.OwningColumn.Name == "Register Name")
                    {
                        int columnIndex = dataGridView1.Columns["Register Number"].Index;
                        int rowindex = dataGridView1.CurrentCell.RowIndex;
                        dataGridView1[columnIndex, rowindex].Value = map.findParam(dataGridView1.CurrentCell.Value.ToString()).register.ToString();
                    }
                }
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }


        }

        private void button1_Click(object sender, EventArgs e)
        {
            StreamWriter outHandle = new StreamWriter("output.txt", true);
            try
            {
                HandleCommands(outHandle,0);
            }
            finally
            {
                ((IDisposable)outHandle).Dispose();
            }
        }

        private void HandleCommands(StreamWriter outHandle, int from)
        {
            for (int i = 0; i < bindingSource1.Count; i++)
            {
                dataGridView1[0, i].Value = false;
                dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.White;
            }
            
            
            for (int i = from; i < bindingSource1.Count; i++)
            {

                if ((i - 2) >= 0)
                {
                    dataGridView1.FirstDisplayedScrollingRowIndex = i - 2;
                }

                try
                {

                    PreformReadOrWrite(i);
                }
                catch (Exception err)
                {
                    bindingSource1[i].errCode = err.Message;
                    //bindingSource1[i].
                }
            }

           
        }

        private void PreformReadOrWrite(int i)
        {
            dataGridView1[0, i].Value = true;
            mapFields mapField = map.findParam(int.Parse(bindingSource1[i].RegisterNumber));
            command.regType tempregType;
            command.RW RWtype;
            command.value_t valueType;


            if (mapField.parameterType == mapFields.paramType.float_t)
                valueType = command.value_t.float_t;
            else
                valueType = command.value_t.word_t;

            if (mapField.registerType == mapFields.regType.holding)
                tempregType = command.regType.holding_t;
            else
                tempregType = command.regType.input_t;



            try
            {
                if (bindingSource1[i].command == DataStorage.commandEnum.read)
                {

                    RWtype = command.RW.read;
                    command tempCommand = new command(valueType, RWtype, tempregType, mapField.baseRegister, bindingSource1[i].Value);
                    tempCommand.DoReadorWrite();
                    if (bindingSource1[i].Value != "")
                    {
                        if (bindingSource1[i].Value != tempCommand.result)
                        {
                            //for (int j = 0; j < dataGridView1.ColumnCount; j++)
                            //{
                            //dataGridView1[j, i].Style.BackColor = Color.Red;

                            //}
                            dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Red;
                            bindingSource1[i].Value = tempCommand.result;
                            bindingSource1[i].success = false;
                        }
                    }
                    else
                    {
                        bindingSource1[i].Value = tempCommand.result;
                    }
                }
                else if (bindingSource1[i].command == DataStorage.commandEnum.write)
                {

                    RWtype = command.RW.write;
                    command tempCommand = new command(valueType, RWtype, tempregType, mapField.baseRegister, bindingSource1[i].Value);
                    tempCommand.DoReadorWrite();
                    //bindingSource1[i].Value = tempCommand.result;
                }
            }
            catch (Exception err)
            {

                bindingSource1[i].errCode = err.Message;
            }

            dataGridView1.Update();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            bindingSource1.Insert(dataGridView1.CurrentCell.RowIndex+1, new DataStorage());
        }

        private void button3_Click(object sender, EventArgs e)
        {
            StreamWriter outHandle = new StreamWriter("output.txt", true);
            try
            {

                HandleCommands(outHandle, dataGridView1.CurrentCell.RowIndex);
            }
            finally
            {
                ((IDisposable)outHandle).Dispose();
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            SaveFileDialog save = new SaveFileDialog();
            save.Filter = "Xml Files (*.xml) | *.xml";
            save.ShowDialog();
            string fileLoc = save.FileName;

            if (save.CheckFileExists)
            {
                if (MessageBox.Show("Are you sure you want to overwrite", "File Exists", MessageBoxButtons.YesNo).ToString() == "Yes")
                {
                    using (StreamWriter outHandle = new StreamWriter(fileLoc))
                    {
                        serializer.Serialize(outHandle, bindingSource1);
                    }
                }
            }
            else
            {
                using (StreamWriter outHandle = new StreamWriter(fileLoc))
                {
                    serializer.Serialize(outHandle, bindingSource1);
                }
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            OpenFileDialog open = new OpenFileDialog();
            open.Filter = "Xml Files (*.xml) | *.xml";
            open.ShowDialog();
            //string fileLoc = open.FileName;
            if (open.CheckFileExists)
            {
                using (StreamReader inHandle = new StreamReader(open.OpenFile()))
                {
                    bindingSource1 = (BindingList<DataStorage>)serializer.Deserialize(inHandle);

                }
            }

            dataGridView1.DataSource = bindingSource1;
            dataGridView1.Refresh();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            PreformReadOrWrite(dataGridView1.CurrentCell.RowIndex);

        }

        private void button7_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < bindingSource1.Count; i++)
            {
                try
                {
                    bindingSource1[i].RegisterName = map.findParam(int.Parse(bindingSource1[i].RegisterNumber)).paramName;
                }
                catch (Exception err)
                {
                    bindingSource1[i].RegisterName = err.Message;
                }
            }
        }

        private void button8_Click(object sender, EventArgs e)
        {
            try
            {
                for (int i = dataGridView1.CurrentCell.RowIndex; i < int.Parse(textBox1.Text) + dataGridView1.CurrentCell.RowIndex; i++)
                {
                    PreformReadOrWrite(i);
                }
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }
        }
    }
}
